﻿using ITSM.Model;
using ITSM.Model.Entity;
using ITSM.Model.Model;
using Microsoft.Extensions.Logging;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace ITSM.Service
{
    public class QRLogin : BaseDB, IQRLogin
    {
        private readonly ILogger _log;
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IUserInfo _userinfo;
        public QRLogin(ILogger<QRLogin> log, IHttpClientFactory httpClientFactory, IUserInfo userinfo)
        {
            _log = log;
            _httpClientFactory = httpClientFactory;
            _userinfo = userinfo;
        }

        public string CreateQR()
        {
            try
            {
                string RYD_LoginId = Guid.NewGuid().ToString();
                RYD_WXQRCode rYD_WXQR = new() { RYD_LoginId = RYD_LoginId, RYD_CreateTime = DateTime.Now };

                return db.Insertable(rYD_WXQR).ExecuteCommand() > 0 ? RYD_LoginId : "";
            }
            catch (Exception e)
            {
                _log.LogError(e.Message);
            }
            return "";
        }

        public string QueryQR(string RYD_LoginId)
        {
            try
            {
                return db.Queryable<RYD_WXQRCode>().Where(res => res.RYD_LoginId == RYD_LoginId).First().WX_Code;
            }
            catch (Exception e)
            {
                _log.LogError(e.Message);
            }
            return "";
        }

        public async Task<bool> UpdataQR(string RYD_LoginId, string WX_Code, string? returnUrl)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(returnUrl))
                {
                    var data = db.Queryable<RYD_WXQRCode>().Where(res => res.RYD_LoginId == RYD_LoginId).First();
                    data.RYD_ModifyTime = DateTime.Now;
                    data.WX_Code = WX_Code; 
                    return db.Updateable(data).ExecuteCommand() > 0;
                }
                else
                {
                    string openId = await _userinfo.OAuth2(WX_Code);
                    for (int i = 0; i < 3; i++)
                    {
                        if (await ReturnUrl(returnUrl, openId, RYD_LoginId))
                        {
                            return true;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _log.LogError(e.Message);
            }
            return false;
        }

        public async Task<bool> ReturnUrl(string returnUrl, string openId,string RYD_LoginId)
        {
            try
            {
                var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, returnUrl);

                httpRequestMessage.Content = new StringContent("{openId:'"+openId+ "',loginId:'"+ RYD_LoginId + "'}", Encoding.UTF8,Application.Json);

                var httpClient = _httpClientFactory.CreateClient();

                //发送请求
                var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
                //判断请求是否成功
                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    //获取数据流
                    using var contentStream = await httpResponseMessage.Content.ReadAsStreamAsync();
                    //转换成string
                    StreamReader reader = new(contentStream);
                    string text = reader.ReadToEnd();
                    if (text.ToLower() == "true")
                    {
                        return true;
                    }
                }
                return false;

            }
            catch (Exception e)
            {
                _log.LogError("调用WX接口查询OpenId错误！{e}", e.Message);
                return false;
            }
        }

    }
}
